package com.uzai.console.service.wechatwork.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.enums.WxqBlacklistTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.wechatwork.wxq.wxgorupblacklist.blacklistprv.WxqWorkBlacklistPrvDto;
import com.uzai.console.dto.wechatwork.wxq.wxgorupblacklist.blacklistprv.WxqWorkBlacklistPrvIdDto;
import com.uzai.console.dto.wechatwork.wxq.wxgorupblacklist.blacklistprv.WxqWorkBlacklistPrvQuery;
import com.uzai.console.entity.es.WxqWorkBlacklistPrv;
import com.uzai.console.entity.es.WxqWorkBlacklistPub;
import com.uzai.console.service.wechatwork.WxqWorkBlacklistPrvService;
import com.uzai.console.vo.wechatwork.wxq.wxgroupblacklist.blacklistprv.WxqWorkBlacklistPrvVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class WxqWorkBlacklistPrvServiceImpl implements WxqWorkBlacklistPrvService {

    Logger logger = LoggerFactory.getLogger(WxqWorkBlacklistPrvServiceImpl.class);

    @Autowired
    private ElasticsearchUtil elasticsearchUtil;

    /**
     * 查询社群私有黑名单列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqWorkBlacklistPrvQuery
     * @return null
     */
    public Page<WxqWorkBlacklistPrvVo> findWxqWorkBlacklistPrvList(WxqWorkBlacklistPrvQuery wxqWorkBlacklistPrvQuery){
        //新建返回到页面的LIST对象
        List<WxqWorkBlacklistPrvVo> wxqWorkBlacklistPrvVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxqWorkBlacklistPrvVo> page = new Page<>();
        wxqWorkBlacklistPrvQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(wxqWorkBlacklistPrvQuery.getMerId())));

        //黑名单类型(0打广告 1刷屏 2同行 3敏感词 4其他)
        if(wxqWorkBlacklistPrvQuery.getType() != null){
            boolQuery.must(QueryBuilders.termQuery("type", wxqWorkBlacklistPrvQuery.getType()));
        }

        //群微信id
        if(StringUtils.isNotBlank(wxqWorkBlacklistPrvQuery.getGroupWxid())){
            boolQuery.must(QueryBuilders.termQuery("groupWxid", wxqWorkBlacklistPrvQuery.getGroupWxid()));
        }

        //微信id
        if(StringUtils.isNotBlank(wxqWorkBlacklistPrvQuery.getWxid())){
            boolQuery.must(QueryBuilders.termQuery("wxid", wxqWorkBlacklistPrvQuery.getWxid()));
        }

        //微信昵称
        if(StringUtils.isNotBlank(wxqWorkBlacklistPrvQuery.getNick())){
            boolQuery.must(QueryBuilders.matchQuery("nick", wxqWorkBlacklistPrvQuery.getNick()));
        }

        //高亮字段
        String highlightField = null;

        searchSourceBuilder.query(boolQuery);

        //排序
        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        ESResult esResult = elasticsearchUtil.searchListData(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, searchSourceBuilder, wxqWorkBlacklistPrvQuery.getSize(), wxqWorkBlacklistPrvQuery.getFromIndex(), null, null, highlightField, wxqWorkBlacklistPrvQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxqWorkBlacklistPrv wxqWorkBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxqWorkBlacklistPrv.class);
                if(wxqWorkBlacklistPrv != null){
                    WxqWorkBlacklistPrvVo wxqWorkBlacklistPrvVo = new WxqWorkBlacklistPrvVo();
                    BeanUtils.copyProperties(wxqWorkBlacklistPrv, wxqWorkBlacklistPrvVo);

                    if(wxqWorkBlacklistPrvVo.getType() != null){
                        WxqBlacklistTypeEnum wxqWorkBlacklistTypeEnum = WxqBlacklistTypeEnum.getById(wxqWorkBlacklistPrvVo.getType());
                        if(wxqWorkBlacklistTypeEnum != null){
                            wxqWorkBlacklistPrvVo.setTypeName(wxqWorkBlacklistTypeEnum.getDesc());
                        }
                    }

                    //查询是否共享黑名单
                    wxqWorkBlacklistPrvVo.setShareStatus(0);  //未共享
                    String wxid = wxqWorkBlacklistPrv.getWxid();
                    if(StringUtils.isNotBlank(wxid)){
                        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, wxid, null);
                        if(map != null){
                            wxqWorkBlacklistPrvVo.setShareStatus(1);  //已经共享
                        }
                    }
                    wxqWorkBlacklistPrvVoList.add(wxqWorkBlacklistPrvVo);
                }
            }
        }

        //返回到页面分页对象
        page.setRecords(wxqWorkBlacklistPrvVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 添加私有黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqWorkBlacklistPrvDto
     * @return null
     */
    @Transactional
    public void addWxqWorkBlacklistPrv(WxqWorkBlacklistPrvDto wxqWorkBlacklistPrvDto){

        if(wxqWorkBlacklistPrvDto.getType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入黑名单类型");
        }

        if(StringUtils.isBlank(wxqWorkBlacklistPrvDto.getWxid())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入微信id");
        }

        if(StringUtils.isBlank(wxqWorkBlacklistPrvDto.getGroupWxid())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群微信id");
        }

        //id为merId_wxid
        String id = wxqWorkBlacklistPrvDto.getMerId() + "_" + wxqWorkBlacklistPrvDto.getGroupWxid() + "_" + wxqWorkBlacklistPrvDto.getWxid();
        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, id, null);
        if(map != null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信id已经在此群黑名单中");
        }

        WxqWorkBlacklistPrv wxqWorkBlacklistPrv = new WxqWorkBlacklistPrv();
        BeanUtils.copyProperties(wxqWorkBlacklistPrvDto, wxqWorkBlacklistPrv);

        Integer now = DateUtil.getNowTime();
        wxqWorkBlacklistPrv.setId(id);
        wxqWorkBlacklistPrv.setCreateTime(now);
        wxqWorkBlacklistPrv.setUpdateTime(now);

        elasticsearchUtil.addData(wxqWorkBlacklistPrv, EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, id);

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 修改私有黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqWorkBlacklistPrvDto
     * @return null
     */
    @Transactional
    public void updateWxqWorkBlacklistPrv(WxqWorkBlacklistPrvDto wxqWorkBlacklistPrvDto){

        if(StringUtils.isBlank(wxqWorkBlacklistPrvDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if(wxqWorkBlacklistPrvDto.getType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入黑名单类型");
        }

        if(StringUtils.isBlank(wxqWorkBlacklistPrvDto.getWxid())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入微信id");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, wxqWorkBlacklistPrvDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有黑名单不存在");
        }

        WxqWorkBlacklistPrv wxqWorkBlacklistPrv = new WxqWorkBlacklistPrv();
        BeanUtils.copyProperties(wxqWorkBlacklistPrvDto, wxqWorkBlacklistPrv);
        Integer now = DateUtil.getNowTime();
        wxqWorkBlacklistPrv.setUpdateTime(now);
        wxqWorkBlacklistPrv.setHimg(wxqWorkBlacklistPrvDto.getHimg());
        wxqWorkBlacklistPrv.setType(wxqWorkBlacklistPrvDto.getType());
        wxqWorkBlacklistPrv.setWxid(wxqWorkBlacklistPrvDto.getWxid());

        elasticsearchUtil.updateDataById(wxqWorkBlacklistPrv, EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, wxqWorkBlacklistPrvDto.getId());

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 移除黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqWorkBlacklistPrvIdDto
     * @return null
     */
    @Transactional
    public void deleteWxqWorkBlacklistPrv(WxqWorkBlacklistPrvIdDto wxqWorkBlacklistPrvIdDto){

        if(StringUtils.isBlank(wxqWorkBlacklistPrvIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, wxqWorkBlacklistPrvIdDto.getId(), null);
        WxqWorkBlacklistPrv wxqWorkBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqWorkBlacklistPrv.class);
        if(wxqWorkBlacklistPrv == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有黑名单不存在");
        }

        //删除私有黑名单
        elasticsearchUtil.deleteDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, wxqWorkBlacklistPrvIdDto.getId());

        //判断是否自己共享了全网黑名单，如果是自己共享的，则同时删除全网黑名单
        if(StringUtils.isNotBlank(wxqWorkBlacklistPrv.getWxid())) {
            Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, wxqWorkBlacklistPrv.getWxid(), null);
            WxqWorkBlacklistPub wxqWorkBlacklistPub = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqWorkBlacklistPub.class);
            if (wxqWorkBlacklistPub != null) {
                //判断是不是该运营商共享的全网黑名单
                if (wxqWorkBlacklistPub.getMerId().longValue() == wxqWorkBlacklistPrvIdDto.getMerId().longValue()) {
                    elasticsearchUtil.deleteDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, wxqWorkBlacklistPrv.getWxid());
                }
            }
        }

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 查询私有黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqWorkBlacklistPrvIdDto
     * @return null
     */
    public WxqWorkBlacklistPrvVo findWxqWorkBlacklistPrv(WxqWorkBlacklistPrvIdDto wxqWorkBlacklistPrvIdDto){
        if(StringUtils.isBlank(wxqWorkBlacklistPrvIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, wxqWorkBlacklistPrvIdDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有黑名单不存在");
        }

        WxqWorkBlacklistPrv wxqWorkBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqWorkBlacklistPrv.class);
        WxqWorkBlacklistPrvVo wxqWorkBlacklistPrvVo = new WxqWorkBlacklistPrvVo();
        BeanUtils.copyProperties(wxqWorkBlacklistPrv, wxqWorkBlacklistPrvVo);

        return wxqWorkBlacklistPrvVo;
    }

    /**
     * 共享全网黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqWorkBlacklistPrvIdDto
     * @return null
     */
    public void shareWxqWorkBlacklistPub(WxqWorkBlacklistPrvIdDto wxqWorkBlacklistPrvIdDto){
        if(StringUtils.isBlank(wxqWorkBlacklistPrvIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, wxqWorkBlacklistPrvIdDto.getId(), null);
        WxqWorkBlacklistPrv wxqWorkBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqWorkBlacklistPrv.class);
        if(wxqWorkBlacklistPrv == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有黑名单不存在");
        }

        Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, wxqWorkBlacklistPrv.getWxid(), null);
        WxqWorkBlacklistPub wxqWorkBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqWorkBlacklistPub.class);
        if(wxqWorkBlacklistPub != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信id已经在共享黑名单里");
        }

        wxqWorkBlacklistPub = new WxqWorkBlacklistPub();
        BeanUtils.copyProperties(wxqWorkBlacklistPrv, wxqWorkBlacklistPub);
        Integer now = DateUtil.getNowTime();
        wxqWorkBlacklistPub.setCreateTime(now);
        wxqWorkBlacklistPub.setUpdateTime(now);
        wxqWorkBlacklistPub.setId(wxqWorkBlacklistPub.getWxid());
        //数据来源(0运营商共享 1官方采集-免费  2收费名单)
        wxqWorkBlacklistPub.setSource(0);
        //增加到全网黑名单
        elasticsearchUtil.addData(wxqWorkBlacklistPub, EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, wxqWorkBlacklistPub.getWxid());

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 取消全网黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqWorkBlacklistPrvIdDto
     * @return null
     */
    public void cancelWxqWorkBlacklistPub(WxqWorkBlacklistPrvIdDto wxqWorkBlacklistPrvIdDto){
        if(StringUtils.isBlank(wxqWorkBlacklistPrvIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, wxqWorkBlacklistPrvIdDto.getId(), null);
        WxqWorkBlacklistPrv wxqWorkBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqWorkBlacklistPrv.class);
        if(wxqWorkBlacklistPrv == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有黑名单不存在");
        }

        Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, wxqWorkBlacklistPrv.getWxid(), null);
        WxqWorkBlacklistPub wxqWorkBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqWorkBlacklistPub.class);
        if(wxqWorkBlacklistPub == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信id不在全网黑名单里");
        }

        //判断是不是该运营商共享的全网黑名单
        if(wxqWorkBlacklistPub.getMerId().longValue() != wxqWorkBlacklistPrvIdDto.getMerId().longValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信id是其他运营商共享到全网黑名单");
        }

        elasticsearchUtil.deleteDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, wxqWorkBlacklistPrv.getWxid());

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }
}
